package gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GraphicsConfigTemplate;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.io.File;
import java.util.ArrayList;

import javax.media.j3d.Canvas3D;
import javax.media.j3d.GraphicsConfigTemplate3D;
import javax.swing.BorderFactory;
import javax.swing.JPanel;


import kernel.AsuvizCore;
import kernel.Volume;

import render.AsuvizRenderer;

public class AsuvizPanelRenderer extends JPanel {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private AsuvizRenderer rendererCore;
	private AsuvizCore asuvizCore;

	public AsuvizPanelRenderer()
	{
		asuvizCore = AsuvizCore.getInstance();
		setBorder(BorderFactory.createTitledBorder("Render"));
		setLayout(new BorderLayout());
		
		GraphicsConfigTemplate3D graphicsTemplate = new GraphicsConfigTemplate3D();
		graphicsTemplate.setDepthSize(24);
		graphicsTemplate.setSceneAntialiasing(GraphicsConfigTemplate.PREFERRED);
		GraphicsConfiguration conf = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getBestConfiguration(graphicsTemplate);
		rendererCore = new AsuvizRenderer(new Canvas3D(conf));
		setCanvas(rendererCore.getCanvas());
		rendererCore.render();
		rendererCore.setLightingSetup("plugin.LightingSetup_003");
	}
	
	public void setStatsRelativePath(String relativePath)
	{
		asuvizCore.setStatRelativePath(relativePath);
	}
	
	public void setCanvas(Canvas3D canvas)
	{
		add(canvas, BorderLayout.CENTER);
	}
	
	public void addFiber(File file, Color color) throws Exception
	{
		asuvizCore.createFiberFromFile(file, color);
		rendererCore.addFiberSet(asuvizCore.getFiberByName(file.getAbsolutePath()));
	}
	
	public void addVolume(File file, Color color) throws Exception
	{
		asuvizCore.createVolumeFromFile(file, color);
		rendererCore.addVolume(asuvizCore.getVolumeByName(file.getAbsolutePath()));
	}
	
	public double getStructureVolumeInMm(String volumeName)
	{
		return asuvizCore.getStructureVolumeInMm(volumeName);
	}

	public String[] getVolumeNames() {
		
		ArrayList<Volume> volumes = asuvizCore.getVolumes();
		String[] volumeNames = new String[volumes.size()];
		for(int i = 0; i < volumes.size(); i++)
		{
			Volume v = volumes.get(i);
			String vName = v.getName();
			vName = vName.substring(vName.lastIndexOf(File.separatorChar) + 1);
			vName = vName.substring(0, vName.lastIndexOf("."));
			volumeNames[i] = vName + " (mm3): " + v.getVolume();
		}
		return volumeNames;
	}

	public Color[] getVolumeColors() {
		ArrayList<Volume> volumes = asuvizCore.getVolumes();
		Color[] volumeColors = new Color[volumes.size()];
		for(int i = 0; i < volumes.size(); i++)
		{
			Volume v = volumes.get(i);
			volumeColors[i] = v.getColor();
		}
		return volumeColors;
	}
}
